package com.mojawa.mj_util.location

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.mojawa.mj_util.time.MJTimeManager
import com.mojawa.mj_util.time.MJTimeUtil

class LocationService : Service() {
    private lateinit var locationManager: LocationManager
    private val points: MutableList<AmapLatLng> = ArrayList()
    private var locationDataManager: MJLocationDataManager? = null
    private var timerManager = MJTimeManager.getInstance()
    private var second: Long? = null

    override fun onCreate() {
        super.onCreate()
        Log.d("LocationService", "Service created")
        locationDataManager = MJLocationDataManager()

        // 初始化 LocationManager
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

        // 启动定位和计时
        startLocation()
        startTimer()
    }

    private fun startTimer() {
        timerManager?.startTimer(object : MJTimeManager.TimerUpdateListener {
            override fun onTimerUpdate(seconds: Long) {
                second = seconds
            }
        })
    }

    private fun startLocation() {
        // 检查权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
        ) {
            // 权限未授予
            Log.e("LocationService", "Location permission not granted")
            return
        }

        // 启动位置更新，每1秒获取一次位置
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            1000L,   // 时间间隔（毫秒）
            1f,      // 距离间隔（米）
            locationListener,
            Looper.getMainLooper()
        )
    }

    // 定位监听器
    private val locationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            if (MJTimeUtil.isPaused) return

            val newLatLng = AmapLatLng(location.latitude, location.longitude)

            // 恢复后的第一个位置更新不计算距离
            if (MJTimeUtil.isFirstLocationAfterResume) {
                Log.d("LocationService", "First location update after resume, not calculating distance")
                points.clear()
                points.add(newLatLng)
                MJTimeUtil.isFirstLocationAfterResume = false
                return
            }

            // 检查上一个点，避免重复记录
            val lastPoint = points.lastOrNull()
            if (lastPoint == null || newLatLng != lastPoint) {
                points.add(newLatLng)
                locationDataManager?.addPoint(listOf(newLatLng))

                // 发送广播通知更新距离
                sendDistanceBroadcast(locationDataManager?.totalDistance, locationDataManager?.getPoints())
            } else {
                Log.d("LocationService", "Same location, skipping distance calculation")
            }
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
        override fun onProviderEnabled(provider: String) {}
        override fun onProviderDisabled(provider: String) {}
    }

    private fun sendDistanceBroadcast(totalDistance: Double?, points: List<AmapLatLng>?) {
        val intent = Intent("RunMiddleDistance")
        intent.putExtra("total_distance", totalDistance)
        val pointsArrayList = ArrayList(points)
        intent.putParcelableArrayListExtra("points", pointsArrayList)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("LocationService", "Service started")

        // 开启前台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "LOCATION_CHANNEL",
                "Location Service Channel",
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(channel)
        }

        val notification: Notification = NotificationCompat.Builder(this, "LOCATION_CHANNEL")
            .setContentTitle("Location Service")
            .setContentText("Running background location tracking")
            .setSmallIcon(android.R.drawable.ic_menu_mylocation)
            .build()

        startForeground(1, notification)
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        locationManager.removeUpdates(locationListener)
        Log.d("LocationService", "Service destroyed, location updates stopped")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}